package com.zhuyi.broadcast.controller;

import com.zhuyi.broadcast.pojo.domain.ElementResourceRelation;
import com.zhuyi.broadcast.pojo.domain.InsertBroadcastTask;
import com.zhuyi.broadcast.pojo.domain.Schedule;
import com.zhuyi.broadcast.pojo.domain.ScheduleProgramRelation;
import com.zhuyi.broadcast.service.ScheduleService;
import com.zhuyi.common.annotation.Log;
import com.zhuyi.common.constant.BroadcastConstants;
import com.zhuyi.common.core.controller.BaseController;
import com.zhuyi.common.core.domain.AjaxResult;
import com.zhuyi.common.core.page.TableDataInfo;
import com.zhuyi.common.enums.BusinessType;
import com.zhuyi.common.utils.DateUtils;
import com.zhuyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * <p>
 *  轮播计划Controller
 * </p>
 *
 * @author dyj
 * @since 2024-12-20
 */
@RestController
@RequestMapping("/broadcast/schedule")
public class ScheduleController extends BaseController {

    @Autowired
    private ScheduleService scheduleService;

    /**
     * 查询轮播计划（列表）
     */
    @GetMapping("/list")
    public TableDataInfo listAvailableSchedules(Schedule schedule) {
        startPage();//分页功能
        List<Schedule> list = scheduleService.list(schedule);//查询轮播计划列表
        return getDataTable(list);  //返回分页后的数据
    }

    /**
     * 查询轮播计划详细信息
     */
    @GetMapping("/{scheduleId}")
    public AjaxResult getInfo(@PathVariable Long scheduleId) {
        Schedule schedule = scheduleService.getById(scheduleId);
        return AjaxResult.success(schedule);
    }

    /**
     * 新增轮播计划
     */
    @Log(title = "轮播计划", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public AjaxResult add(@RequestBody Schedule schedule) throws Exception {
        schedule.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        schedule.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        schedule.setCreateTime(DateUtils.getNowDate());
        schedule.setUpdateTime(DateUtils.getNowDate());
        schedule.setState(BroadcastConstants.RESOURCE_STATE_PENDING);
        return toAjax(scheduleService.save(schedule));
    }

    /**
     * 删除轮播计划
     */
    @Log(title = "轮播计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scheduleId}")
    public AjaxResult remove(@PathVariable Long scheduleId) {
        return toAjax(scheduleService.removeById(scheduleId));
    }

    /**
     * 提交插播任务
     */
    @PostMapping("/insertBroadcast")
    public AjaxResult insertBroadcast(@RequestBody InsertBroadcastTask insertBroadcastTask) {
        try {
            // 提交插播任务
            scheduleService.insertBroadcastTask(insertBroadcastTask);
            return AjaxResult.success("插播任务提交成功！");
        } catch (Exception e) {
            return AjaxResult.error("插播任务提交失败：" + e.getMessage());
        }
    }




    /**
     * 查询轮播计划中的节目列表
     */
    @GetMapping("/{scheduleId}/program")
    public AjaxResult getProgramList(@PathVariable Long scheduleId) {
        List<ScheduleProgramRelation> updatedschedule = scheduleService.getprogramlistByScheduleId(scheduleId);
        return success(updatedschedule);
    }

    /**
     * 添加节目到轮播计划
     */
    @Log(title = "轮播计划", businessType = BusinessType.INSERT)
    @PostMapping("/program")
    public AjaxResult addProgramToSchedule(@RequestParam Long scheduleId,
                                           @RequestParam Long programId) {

        boolean success = scheduleService.addProgramToSchedule(programId, scheduleId);
        return success ? success("节目添加成功") : error("节目添加失败");
    }

    /**
     * 删除节目（从轮播计划中）
     */
    @Log(title = "轮播计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/program")
    public AjaxResult removeProgramFromSchedule(@RequestParam Long scheduleId,
                                                @RequestParam Long programId) {
        try {
            boolean success = scheduleService.removeProgramFromSchedule(scheduleId, programId);
            return success ? AjaxResult.success("节目从轮播计划中移除成功") : AjaxResult.error("节目从轮播计划中移除失败");
        } catch (Exception e) {
            return AjaxResult.error("移除节目失败: " + e.getMessage());
        }
    }

    /**
     * 更新节目（轮播计划中）
     * @param params 请求体中的参数
     * @return AjaxResult 返回更新后的轮播计划信息
     */
    @PutMapping("/program")
    public AjaxResult updateschedule(@RequestBody Map<String, String> params) {
        Long scheduleId = Long.valueOf(params.get("scheduleId"));
        Long programId = Long.valueOf(params.get("programId"));

        // 参数检查
        if (programId == null || scheduleId == null) {
            return error("Program ID and schedule ID are required");
        }

        // 更新轮播计划
        boolean result = scheduleService.updateSchedule(programId, scheduleId, params);
        if (!result) {
            return error("Failed to update schedule");
        }

        // 返回更新后的轮播计划信息
        List<ScheduleProgramRelation> updatedschedule = scheduleService.getprogramlistByScheduleId(scheduleId);
        return success(updatedschedule);
    }
}
